package com.pphh.demo.provider;

import com.alibaba.csp.sentinel.init.InitExecutor;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.pphh.demo.DemoService;

import java.io.IOException;
import java.util.Collections;

/**
 * A example shows how to control the speed of dubbo rpc calls by QPS
 * this example make reference to sentinel's demo examples.
 * https://github.com/alibaba/Sentinel
 *
 * @author pphh
 * @date 2019/1/17
 */
public class ProviderBootstrap {

    private static final String RES_KEY = "com.pphh.demo.DemoService:sayHello(java.lang.String)";

    public static void main(String[] args) throws IOException {
        InitExecutor.doInit();
        initFlowRule();

        ServiceConfig<DemoService> service = new ServiceConfig<>();
        service.setApplication(new ApplicationConfig("first-dubbo-provider"));
        service.setRegistry(new RegistryConfig("multicast://224.5.6.7:1234"));
        service.setInterface(DemoService.class);
        service.setVersion("1.0.0");
        service.setRef(new DemoServiceImpl());
        service.export();
        System.out.println("provider is running.");
        System.in.read();
    }

    /**
     * control the flow by QPS
     * RuleConstant.FLOW_GRADE_QPS
     */
    private static void initFlowRule() {
        FlowRule flowRule = new FlowRule();
        flowRule.setResource(RES_KEY);
        flowRule.setCount(10);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setLimitApp("first-dubbo-consumer");
        FlowRuleManager.loadRules(Collections.singletonList(flowRule));
    }

}
